// 简单的交互效果
document.addEventListener('DOMContentLoaded', function() {
    // 为导航链接添加悬停效果
    const navLinks = document.querySelectorAll('nav a');
    navLinks.forEach(link => {
        link.addEventListener('mouseover', function() {
            this.style.backgroundColor = 'rgba(255,255,255,0.2)';
            this.style.padding = '0.5rem';
            this.style.borderRadius = '4px';
        });

        link.addEventListener('mouseout', function() {
            this.style.backgroundColor = 'transparent';
            this.style.padding = '0';
        });
    });

    // 为按钮添加点击效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        button.addEventListener('click', function() {
            this.style.backgroundColor = '#45a049';
            setTimeout(() => {
                this.style.backgroundColor = '#4CAF50';
            }, 200);
        });
    });
});

// 登录表单验证
document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');

    // 登录表单验证
    if (loginForm) {
        loginForm.addEventListener('submit', function(event) {
            let isValid = true;

            // 验证用户名
            const username = document.getElementById('username');
            const usernameError = document.getElementById('usernameError');
            if (!username.value.trim()) {
                username.classList.add('error');
                usernameError.textContent = '用户名不能为空';
                usernameError.style.display = 'block';
                isValid = false;
            } else {
                username.classList.remove('error');
                usernameError.style.display = 'none';
            }

            // 验证密码
            const password = document.getElementById('password');
            const passwordError = document.getElementById('passwordError');
            if (!password.value) {
                password.classList.add('error');
                passwordError.textContent = '密码不能为空';
                passwordError.style.display = 'block';
                isValid = false;
            } else if (password.value.length < 6) {
                password.classList.add('error');
                passwordError.textContent = '密码长度不能少于6位';
                passwordError.style.display = 'block';
                isValid = false;
            } else {
                password.classList.remove('error');
                passwordError.style.display = 'none';
            }

            if (!isValid) {
                event.preventDefault();
            }
        });
    }

    // 注册表单验证和提交
    if (registerForm) {
        registerForm.addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止默认表单提交
            let isValid = true;

            // 验证用户名
            const username = document.getElementById('registerUsername');
            const usernameError = document.getElementById('registerUsernameError');
            if (!username.value.trim()) {
                username.classList.add('error');
                usernameError.textContent = '用户名不能为空';
                usernameError.style.display = 'block';
                isValid = false;
            } else {
                username.classList.remove('error');
                usernameError.style.display = 'none';
            }

            // 验证邮箱
            const email = document.getElementById('email');
            const emailError = document.getElementById('emailError');
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!email.value.trim()) {
                email.classList.add('error');
                emailError.textContent = '邮箱不能为空';
                emailError.style.display = 'block';
                isValid = false;
            } else if (!emailRegex.test(email.value)) {
                email.classList.add('error');
                emailError.textContent = '请输入有效的邮箱地址';
                emailError.style.display = 'block';
                isValid = false;
            } else {
                email.classList.remove('error');
                emailError.style.display = 'none';
            }

            // 验证密码
            const password = document.getElementById('registerPassword');
            const passwordError = document.getElementById('registerPasswordError');
            if (!password.value) {
                password.classList.add('error');
                passwordError.textContent = '密码不能为空';
                passwordError.style.display = 'block';
                isValid = false;
            } else if (password.value.length < 6) {
                password.classList.add('error');
                passwordError.textContent = '密码长度不能少于6位';
                passwordError.style.display = 'block';
                isValid = false;
            } else {
                password.classList.remove('error');
                passwordError.style.display = 'none';
            }

            // 验证确认密码
            const confirmPassword = document.getElementById('confirmPassword');
            const confirmPasswordError = document.getElementById('confirmPasswordError');
            if (!confirmPassword.value) {
                confirmPassword.classList.add('error');
                confirmPasswordError.textContent = '请确认密码';
                confirmPasswordError.style.display = 'block';
                isValid = false;
            } else if (confirmPassword.value !== password.value) {
                confirmPassword.classList.add('error');
                confirmPasswordError.textContent = '两次密码输入不一致';
                confirmPasswordError.style.display = 'block';
                isValid = false;
            } else {
                confirmPassword.classList.remove('error');
                confirmPasswordError.style.display = 'none';
            }

            if (!isValid) {
                event.preventDefault();
            }
            if (isValid) {
                // 准备JSON数据
                const formData = {
                    username: document.getElementById('registerUsername').value,
                    email: document.getElementById('email').value,
                    password: document.getElementById('registerPassword').value
                };

                // 发送POST请求
                fetch('/api/users/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('服务器响应错误: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    const resultDiv = document.getElementById('registerResult');
                    if (data.success) {
                        resultDiv.textContent = '注册成功！即将跳转到登录页面...';
                        resultDiv.style.color = 'green';
                        // 3秒后跳转到登录页面
                        setTimeout(() => {
                            window.location.href = '/login';
                        }, 3000);
                    } else {
                        resultDiv.textContent = '注册失败: ' + data.message;
                        resultDiv.style.color = 'red';
                    }
                    resultDiv.style.display = 'block';
                })
                .catch(error => {
                    console.error('注册请求失败:', error);
                    const resultDiv = document.getElementById('registerResult');
                    resultDiv.textContent = '注册请求失败: ' + error.message;
                    resultDiv.style.color = 'red';
                    resultDiv.style.display = 'block';
                });
            }
        });
    }
});

// 视频悬停播放功能
document.addEventListener('DOMContentLoaded', function() {
    const videos = document.querySelectorAll('.hover-video');
    videos.forEach(video => {
        // 鼠标悬停时播放
        video.addEventListener('mouseenter', function() {
            this.play();
        });
        
        // 鼠标离开时暂停并重置到开始
        video.addEventListener('mouseleave', function() {
            this.pause();
            this.currentTime = 0;
        });
        
        // 点击视频可以暂停/播放
        video.addEventListener('click', function() {
            if (this.paused) {
                this.play();
            } else {
                this.pause();
            }
        });
    });
});

// 添加资源加载错误处理
// 处理默认头像的辅助函数
function handleDefaultAvatar(imgElement) {
    // 检查当前图片路径是否已经是默认头像
    if (imgElement.src.includes('/images/default-avatar.jpg')) {
        // 如果已经是默认头像加载失败，则隐藏图片
        imgElement.style.display = 'none';
    } else {
        // 尝试设置默认占位图
        const defaultImg = new Image();
        defaultImg.onload = () => {
            imgElement.src = '/images/default-avatar.jpg';
        };
        defaultImg.onerror = () => {
            imgElement.style.display = 'none';
        };
        defaultImg.src = '/images/default-avatar.jpg';
    }
}

// 简单的交互效果
document.addEventListener('DOMContentLoaded', function() {
    // 为导航链接添加悬停效果
    const navLinks = document.querySelectorAll('nav a');
    navLinks.forEach(link => {
        link.addEventListener('mouseover', function() {
            this.style.backgroundColor = 'rgba(255,255,255,0.2)';
            this.style.padding = '0.5rem';
            this.style.borderRadius = '4px';
        });

        link.addEventListener('mouseout', function() {
            this.style.backgroundColor = 'transparent';
            this.style.padding = '0';
        });
    });

    // 为按钮添加点击效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        button.addEventListener('click', function() {
            this.style.backgroundColor = '#45a049';
            setTimeout(() => {
                this.style.backgroundColor = '#4CAF50';
            }, 200);
        });
    });
});

// 视频悬停播放功能
document.addEventListener('DOMContentLoaded', function() {
    const videos = document.querySelectorAll('.hover-video');
    videos.forEach(video => {
        video.addEventListener('mouseenter', function() {
            this.play();
        });
        
        video.addEventListener('mouseleave', function() {
            this.pause();
            this.currentTime = 0;
        });
        
        video.addEventListener('click', function() {
            if (this.paused) {
                this.play();
            } else {
                this.pause();
            }
        });
    });
});

// 确保在DOM加载完成后只执行一次
document.addEventListener('DOMContentLoaded', function() {
    // 导航链接效果
    const navLinks = document.querySelectorAll('nav a');
    navLinks.forEach(link => {
        link.addEventListener('mouseover', function() {
            this.style.backgroundColor = 'rgba(255,255,255,0.2)';
            this.style.padding = '0.5rem';
            this.style.borderRadius = '4px';
        });

        link.addEventListener('mouseout', function() {
            this.style.backgroundColor = 'transparent';
            this.style.padding = '0';
        });
    });

    // 按钮点击效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        button.addEventListener('click', function() {
            this.style.backgroundColor = '#45a049';
            setTimeout(() => {
                this.style.backgroundColor = '#4CAF50';
            }, 200);
        });
    });

    // 视频悬停播放功能
    const videos = document.querySelectorAll('.hover-video');
    videos.forEach(video => {
        video.addEventListener('mouseenter', function() {
            this.play();
        });
        
        video.addEventListener('mouseleave', function() {
            this.pause();
            this.currentTime = 0;
        });
        
        video.addEventListener('click', function() {
            if (this.paused) {
                this.play();
            } else {
                this.pause();
            }
        });
    });

    // 表单验证代码...
    // （保留原有的登录和注册表单验证逻辑）

    // 添加错误处理
    handleResourceErrors();
});

// 替换现有的handleResourceErrors函数
function handleResourceErrors() {
    // 处理视频加载错误
    const videos = document.querySelectorAll('video');
    videos.forEach(video => {
        video.addEventListener('error', function(e) {
            console.error('视频加载失败:', e.target.src);
            // 隐藏失败的视频元素
            const container = this.parentElement;
            if (container) {
                container.innerHTML = '<div class="video-placeholder">视频资源不可用</div>';
            }
            // 阻止错误冒泡到控制台显示
            e.preventDefault();
            e.stopPropagation();
        });
    });
    
    // 处理图片加载错误 - 修改这部分逻辑以解决头像显示不一致的问题
    const images = document.querySelectorAll('img');
    images.forEach(img => {
        // 确保图片路径正确
        // 只处理头像图片的路径问题
        if (img.classList.contains('user-avatar') || img.alt === '用户头像') {
            // 添加错误事件监听器
            img.addEventListener('error', function(e) {
                console.error('头像加载失败:', e.target.src);
                
                // 检查是否已经是默认头像
                if (!e.target.src.includes('/images/default-avatar.jpg')) {
                    // 尝试使用默认头像
                    const defaultImg = new Image();
                    defaultImg.onload = () => {
                        this.src = '/images/default-avatar.jpg';
                    };
                    defaultImg.onerror = () => {
                        this.style.display = 'none';
                    };
                    defaultImg.src = '/images/default-avatar.jpg';
                } else {
                    this.style.display = 'none';
                }
                
                // 阻止错误冒泡
                e.preventDefault();
                e.stopPropagation();
            });
        }
    });
}

// 确保在DOM加载完成后只执行一次
document.addEventListener('DOMContentLoaded', function() {
    // 导航链接效果
    const navLinks = document.querySelectorAll('nav a');
    navLinks.forEach(link => {
        link.addEventListener('mouseover', function() {
            this.style.backgroundColor = 'rgba(255,255,255,0.2)';
            this.style.padding = '0.5rem';
            this.style.borderRadius = '4px';
        });

        link.addEventListener('mouseout', function() {
            this.style.backgroundColor = 'transparent';
            this.style.padding = '0';
        });
    });

    // 按钮点击效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        button.addEventListener('click', function() {
            this.style.backgroundColor = '#45a049';
            setTimeout(() => {
                this.style.backgroundColor = '#4CAF50';
            }, 200);
        });
    });

    // 视频悬停播放功能
    const videos = document.querySelectorAll('.hover-video');
    videos.forEach(video => {
        video.addEventListener('mouseenter', function() {
            this.play();
        });
        
        video.addEventListener('mouseleave', function() {
            this.pause();
            this.currentTime = 0;
        });
        
        video.addEventListener('click', function() {
            if (this.paused) {
                this.play();
            } else {
                this.pause();
            }
        });
    });

    // 表单验证代码...
    // （保留原有的登录和注册表单验证逻辑）

    // 添加错误处理
    handleResourceErrors();
});

// 主页面通用逻辑

document.addEventListener('DOMContentLoaded', function() {
    // 处理导航栏滚动效果
    const header = document.querySelector('header');
    let lastScrollTop = 0;
    
    window.addEventListener('scroll', function() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        
        if (scrollTop > 50) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
        
        lastScrollTop = scrollTop;
    });
    
    // 处理分类导航的滚动效果
    const categoryNav = document.querySelector('.category-nav');
    if (categoryNav) {
        const headerHeight = header.offsetHeight;
        
        window.addEventListener('scroll', function() {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            
            if (scrollTop > headerHeight) {
                categoryNav.classList.add('sticky');
            } else {
                categoryNav.classList.remove('sticky');
            }
        });
    }
});
